import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_rider/main/widgets/ext/u_layout.dart';
import 'package:flutter_rider/main/widgets/ext/u_shape.dart';
import 'package:flutter_rider/main/widgets/ext/u_text.dart';
import 'package:flutter_rider/main/widgets/ext/u_title_layout.dart';
import 'package:flutter_rider/main/widgets/state/state_layout.dart';
import 'package:flutter_rider/utils/screen_fit.dart';
import 'package:flutter_rider/main/widgets/ui_constant.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:flutter_rider/generated/r.dart';
import 'package:flutter_rider/api/api.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter_rider/event/click_far_call_event.dart';
import 'package:flutter_rider/main.dart';


class FarCallPage extends StatefulWidget {
  String carNo;
  String carId;
  String wmNo;
  FarCallPage(this.carNo ,this.carId, {this.wmNo = "",Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return FarCallPageState();
  }
}

class FarCallPageState extends State<FarCallPage> {
  final StateLayoutController _stateLayoutController = StateLayoutController();
  final ScrollController _scrollController = ScrollController();
  int _currentActiveIndex = 0;
  List _messages = [];
  List _data = [];
  bool _canClick = true;
  String _msg = "发送";
  int _times = 10;
  Timer? _timer;
  @override
  void initState() {
    super.initState();
    _getTimes();
  }

  @override
  void dispose() {
    super.dispose();
    _timer?.cancel();
    _recordLastSecond();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: UIColor.color_main,
      appBar: UTitleLayout.getBackTitle(context, widget.carNo+"远程呼叫"),
      body: StateLayout(
        url: "/car/remote_cmd_list",
        controller: _stateLayoutController,
        childBuilder: _renderContent,
        dataCallback: (data) {
          _data = data;
        },
      ).padding(EdgeInsets.only(left: MediaQuery.of(context).padding.left, right: MediaQuery.of(context).padding.right)),
    );
  }

  Widget _renderContent(dynamic data) {
    return Column(
        children: [
          Expanded(
              child:Container(
                  child: MediaQuery.removePadding(
                      removeBottom: true,
                      context: context,
                      child: ListView.builder(
                        itemCount: _messages.length,
                        controller: _scrollController,
                        itemBuilder: _renderItem,
                        shrinkWrap: true,
                      )
                  )
              )
          ),
          _renderButtom()
        ],
      );
  }

  Widget _renderItem(BuildContext context, int index) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.end,
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.end,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            UShape.getCircle(
                size: 8.rpx,
                color:  _messages[index]["status"] == -1 ?  const Color(0xffE34D59) : const Color(0xff00A870)
            ),
            Container(
              padding: EdgeInsets.symmetric(horizontal: 15.rpx,vertical: 9.rpx),
              margin: EdgeInsets.symmetric(horizontal: 8.rpx),
              decoration: const BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.all(Radius.circular(8.0))
              ),
              child: Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text(
                    _messages[index]["name"],
                    style: TextStyle(
                      fontSize: 14.rpx,
                      color: UIColor.color_t5,
                      backgroundColor: UIColor.color_content,
                    ),
                  ),
                ],
              ),
            ),
            SvgPicture.asset(R.image_logo2, width: 40.rpx, height: 40.rpx),
            16.wspace
          ],
        ),
        6.hspace,
        Container(
          margin: EdgeInsets.only(right: 66.rpx),
          child: UText.get(_messages[index]["time"], UIColor.color_t8, 12.rpx),
        ),
        18.hspace,
      ],
    );
  }

  Widget _renderButtom() {
   return Container(
       decoration: const BoxDecoration(
         color: UIColor.color_content,
       ),
       child:Column (
         children: [
           Wrap(
             children: _data.asMap().keys.map((index) => _renderOrder(index)).toList(),
           ),
           Padding(
              padding: EdgeInsets.all(12.rpx),
              child: UText.getBkButton(
                _msg,
                16.rpx,
                bkColor: _canClick ? UIColor.color_primary : UIColor.color_t7,
                radius: 12.rpx,
                width: double.infinity,
                height: 48.rpx,
                onPressed: _onClickSent,
              ),
            )
         ]
      )
   );
  }

  Widget _renderOrder(int index ) {
    return Container(
      width: 74.rpx,
      padding: EdgeInsets.only(top: 5.rpx,bottom:5.rpx),
      margin: EdgeInsets.only(left:8.rpx, right: 8.rpx,top:8.rpx),
      decoration: BoxDecoration(
          color: _currentActiveIndex == index ?UIColor.color_primary:UIColor.color_content,
          border: Border.all(width: 1.rpx,color: _currentActiveIndex == index ?UIColor.color_primary:const Color(0xffE7E7E7)),
          borderRadius: const BorderRadius.all(Radius.circular(60.0))
      ),
      child: GestureDetector(
          onTap: () {
            setState(() {
              _currentActiveIndex = index;
            });
          },
          child: UText.get(_data[index]["remark"], _currentActiveIndex == index ?UIColor.color_content:UIColor.color_t5, 14.rpx, textAlign: TextAlign.center)
      )
    );
  }

  void _onClickSent() {
    if(!_canClick) return;
    setState(() {
      _msg = "${_times}s后发送";
      _canClick = false;
    });
    var json = _getPostJson();
    var url = "/car/remote_cmd";
    DateTime dateTime= DateTime.now();
    var hour = dateTime.hour.toString();
    var minute = dateTime.minute<10?'0'+ dateTime.minute.toString() : dateTime.minute.toString();
    var second = dateTime.second<10?'0'+ dateTime.second.toString() : dateTime.second.toString();
    var time =  hour + ":" + minute + ":" + second;
    Api.submitx(context, url, data: json, progress: false, success: (data) {
      _messages.add({"name":_data[_currentActiveIndex]["remark"],"status":1,"time":time});
      setState(() {
        _messages = _messages;
      });
      Future.delayed(const Duration(milliseconds: 200), () {
        _scrollController.jumpTo(_scrollController.position.maxScrollExtent);
      });
    }, failTip: "提交失败", fail: (_) {
      _messages.add({"name":_data[_currentActiveIndex]["remark"],"status":-1,"time":time});
      setState(() {
        _messages = _messages;
      });
      Future.delayed(const Duration(milliseconds: 200), () {
        _scrollController.jumpTo(_scrollController.position.maxScrollExtent);
      });
    });
    _timer = Timer.periodic(Duration(milliseconds: 1000), (timer) {
      _countDown();
    });
  }

  dynamic _getPostJson() {
    var json = {};
    json["car_id"] = widget.carId;
    json["cmd"] = _data[_currentActiveIndex]["remark_type"];
    json["waybill_mission_no"] = widget.wmNo;
    return json;
  }

  _getTimes() async {
    var _sp = await SharedPreferences.getInstance();
    int _second = _sp.getInt("_second") as int;
    _times = _second >0?_second : _times;
    if(_second > 0) {
      setState(() {
        _msg = "${_times}s后发送";
        _canClick = false;
      });
      _timer = Timer.periodic(Duration(milliseconds: 1000), (timer) {
        _countDown();
      });
    }
  }

  void _countDown() {
    if(_times <= 0 ) {
      setState(() {
        _msg = "发送";
        _canClick = true;
        _times = 10;
      });
      _timer?.cancel();
    } else {
      print("0000${_times}");
      setState(() {
        _msg = "${_times}s后发送";
        _canClick = false;
      });
      _times -= 1;
    }
  }

   _recordLastSecond() async {
    var _sp = await SharedPreferences.getInstance();
    int _second = _times ==10?0:_times;
    _sp.setInt("_second", _second);
    eventBus.fire(ClickFarCallEvent());
  }
}